class DocController < ApplicationController
  scaffold :document
  before_filter :login_required, :except => [ :list, :index, :show ]
  before_filter :author_required, :only => [:edit, :destroy, :update, :promote, :demote, :approve, :reject]
  
  def create
   @document = Document.new(params[:document])
   @document.user=current_user
   if @document.save
     flash[:notice] = "Document was successfully created for #{ current_user.login }"
     redirect_to :action => "list"
   else
     render_scaffold('new')
   end
  end
  
  def list
    @documents=Document.find_active_documents( current_user.id )
    render :action=> :list
  end
  
  def show
    @document=Document.find(params[:id])
    @document_actions={
      "Back" => {:action => :list }
    }
    if logged_in? and @document.user == current_user
      if @document.document_state_id == 3
        @document_actions["Approve"] = { :action => :approve, :id => @document.id }
        @document_actions["Reject"] = { :action => :reject, :id => @document.id }
      elsif @document.document_state_id <= 3
#        @document_actions["Promote (#{DocumentState.find(@document.next_state).name})"] = { :action => :promote, :id => @document.id }
         @document_actions["Promote"] = { :action => :promote, :id => @document.id }
      end
      if @document.document_state_id == 2
        @document_actions["Demote"] = {:action => :demote, :id => @document.id }
      end
      if @document.document_state_id == 1
        @document_actions["Edit"] = {:action => :edit, :id=> @document.id }
        @document_actions["Delete"] = {:action => :destroy, :id=> @document.id, :confirm => "Are you sure?", :method => :post }
      end
    end
    
    if logged_in? and @document.user != current_user and @document.document_state_id == 2
      @document_actions["Add a comment"] = {:controller => :comment, :action => :new, :commentable_type => @document.class.to_s, :commentable_id => @document.id }
    end
  end 
  
  def author_required
    @document=Document.find(params[:id])
    if @document.user != current_user
      flash[:notice] = "Documents can only be modified by their owners"
      redirect_to :action => "show", :id => @document.id
      false
    end
    true
  end
  
  def find_my_drafts
    @documents=Document.find(:all, :conditions => { 
      :user_id => current_user.id, 
      :document_state_id => DocumentState.find_by_name("Draft") 
    })
  end
  
  def promote
    @document=Document.find(params[:id])
    @document.promote
    redirect_to :action => :show, :id => @document.id
  end

  def demote
    @document=Document.find(params[:id])
    @document.demote
    redirect_to :action => :show, :id => @document.id
  end

  
  def approve
    @document=Document.find(params[:id])
    @document.approve
    redirect_to :action => :show, :id => @document.id
  end
  
  def reject
    @document=Document.find(params[:id])
    @document.reject
    redirect_to :action => :show, :id => @document.id
  end
  
end
